<?php
class Reg extends MY_Controller{
	
	public $arrTpl = array();
	public function __construct()
	{
		parent::__construct();
	
		$this->load->model('account/account_m');
	
		$this->load->helper('account');
	
		
		$this->load->config('oauth2');

		$this->arrTpl = $this->config->item('my_session_key');
	}
	
	public function index()
	{

		$this->m_arrSub = array(
				'common/header'  =>  'index',
				'common/footer'  => 'index',
		);
		
		$this->getSub();
		
		$this->data['ajaxUrl'] = array(
				'login' => "index.php/account/login",
				'reg'   => "index.php/account/reg/toreg",
				);
		
		$this->load->view('account/reg',$this->data);
	}
	// 注册
	public function toreg()
	{
		$email = $this->input->post('email',true);
	
		$pwd   = $this->input->post('pwd',true);
		
		$name = $this->input->post('name',true);
	
		if (!filter_var($email,FILTER_VALIDATE_EMAIL))
		{
			$this->data['status'] = 0;
			$this->data['data']['msg'] = '邮箱不正确';
		}
		else
		{
			// 检查邮箱
				
			$arrUser = $this->account_m->getAccount(array('email' => $email));
				
			if (!empty($arrUser))
			{
				$this->data['status'] = 0;
				$this->data['data']['msg'] = '邮箱已经存在了';
			}
			else
			{
				$toAdd = array(
						'email' => $email,
						'pwd'   => $pwd,
						'name' => $name
				);
	
				$account_id = $this->account_m->addAccount($toAdd);
				
				$this->addPlatfromData($account_id);
				
				$arrUser = $this->account_m->getAccount(array('id' => $account_id));
	
				$this->my_member->login($arrUser);
				
				$this->data['status'] = 0;
				$this->data['data']['msg'] = '注册成功了';
	
			}
		}
		
		echo json_encode($this->data);
	}
	
	private function addPlatfromData($accountID)
	{
		foreach ($this->arrTpl as $sessionKey => $type)
		{
			// 平台数据更新
			if ($this->session->userdata($sessionKey) != false)
			{
				$sessionData = $this->session->userdata($sessionKey);
				$addData = array(
						'accountID' => $accountID,
						'platformID'=> $type,
						'addTime'   => date('Y-m-d H:i:s',time()),
						'openID'  	=> $sessionData['openID'],
						'token'   	=> $sessionData['token'],
						'retoken' 	=> $sessionData['retoken'],
						'outTime' 	=> $sessionData['outTime'],
			
				);
				$this->account_m->addPlatform($addData);
			
				unset($this->session->unset_userdata[$sessionKey]);
			}
		}
		
		
	}
}